"""
系统相关路由
"""

from fastapi import APIRouter, HTTPException
from datetime import datetime
import psutil
import platform

from models.common import StandardResponse
from config import get_settings

router = APIRouter(prefix="/system", tags=["系统"])
settings = get_settings()

@router.get("/ping", response_model=StandardResponse, summary="服务器连接测试")
async def ping() -> StandardResponse:
    """
    服务器连接测试接口
    
    用于检测服务器是否正常运行
    """
    return StandardResponse(
        success=True,
        message="pong",
        data={
            "server_time": datetime.now().isoformat(),
            "status": "running"
        }
    )

@router.get("/info", response_model=StandardResponse, summary="获取服务器信息")
async def get_system_info() -> StandardResponse:
    """
    获取服务器基本信息
    
    返回服务器的基本配置和运行状态
    """
    try:
        # 获取系统信息
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        system_info = {
            "server_name": settings.app_name,
            "version": settings.app_version,
            "api_version": "v1",
            "environment": "development" if settings.debug else "production",
            "uptime": "运行中",
            "system": {
                "platform": platform.system(),
                "platform_release": platform.release(),
                "platform_version": platform.version(),
                "architecture": platform.machine(),
                "processor": platform.processor(),
                "python_version": platform.python_version()
            },
            "performance": {
                "cpu_usage": f"{cpu_percent}%",
                "memory_usage": f"{memory.percent}%",
                "memory_total": f"{memory.total / (1024**3):.2f} GB",
                "memory_available": f"{memory.available / (1024**3):.2f} GB",
                "disk_usage": f"{disk.percent}%",
                "disk_total": f"{disk.total / (1024**3):.2f} GB",
                "disk_free": f"{disk.free / (1024**3):.2f} GB"
            },
            "config": {
                "debug_mode": settings.debug,
                "host": settings.host,
                "port": settings.port,
                "database_type": "SQLite" if "sqlite" in settings.database_url else "MySQL"
            }
        }
        
        return StandardResponse(
            success=True,
            message="获取服务器信息成功",
            data=system_info
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取系统信息失败: {str(e)}"
        )

@router.get("/health", response_model=StandardResponse, summary="健康检查")
async def health_check() -> StandardResponse:
    """
    系统健康检查接口
    
    检查各个组件的运行状态
    """
    try:
        health_status = {
            "status": "healthy",
            "checks": {
                "database": "connected",  # 实际应用中应该检查数据库连接
                "redis": "connected",     # 实际应用中应该检查Redis连接
                "disk_space": "sufficient",
                "memory": "sufficient"
            },
            "timestamp": datetime.now().isoformat()
        }
        
        # 检查磁盘空间
        disk = psutil.disk_usage('/')
        if disk.percent > 90:
            health_status["checks"]["disk_space"] = "warning"
            health_status["status"] = "warning"
        
        # 检查内存使用
        memory = psutil.virtual_memory()
        if memory.percent > 90:
            health_status["checks"]["memory"] = "warning"
            health_status["status"] = "warning"
        
        return StandardResponse(
            success=True,
            message="系统健康检查完成",
            data=health_status
        )
        
    except Exception as e:
        return StandardResponse(
            success=False,
            message="健康检查失败",
            error=str(e)
        )